//
//  HKEssenceViewController.m
//  BaiSiBuDeJie
//
//  Created by 胡锦涛 on 2018/11/29.
//  Copyright © 2018 胡锦涛. All rights reserved.
/*
 思路：
 精华控制器添加一个UIScrollView, UIScrollView上添加五个UITableView，且每个UITableView可以上下滑动、互不影响，每个TableView又可以左右切换。(超出scrollView部分会被剪掉)
 // UIBarButtonItem:描述按钮具体的内容
 // UINavigationItem:设置导航条上内容(左边,右边,中间)
 // tabBarItem: 设置tabBar上按钮内容(tabBarButton)
 */

#import "HKEssenceViewController.h"
#import "HKTitleButton.h"

#import "HKAllViewController.h"
#import "HKVideoViewController.h"
#import "HKVoiceViewController.h"
#import "HKWordViewController.h"
#import "HKPictureViewController.h"

@interface HKEssenceViewController ()<UIScrollViewDelegate>
/** 用来存放所有子控制器view的scrollView */
@property (nonatomic, weak) UIScrollView *scrollView;
/** 标题栏 */
@property (nonatomic, weak) UIView *titlesView;
/** 标题下划线 */
@property (nonatomic, weak) UIView *titleUnderline;
/** 上一次点击的标题按钮 */
@property (nonatomic, weak) HKTitleButton *previousClickedTitleButton;
@end

@implementation HKEssenceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = kWhiteColor;
    // 初始化子控制器
    [self setupAllChildVcs];
    
    // 设置导航条
    [self setupNavBar];
    
    // scrollView
    [self setupScrollView];
    
    // 标题栏
    [self setupTitlesView];
    
    // 添加第0个子控制器的view
    [self addChildVcViewIntoScrollView:0];

}
/**
 *  初始化子控制器，分模块管理
 */
- (void)setupAllChildVcs
{
    [self addChildViewController:[[HKAllViewController alloc] init]];
    [self addChildViewController:[[HKVideoViewController alloc] init]];
    [self addChildViewController:[[HKVoiceViewController alloc] init]];
    [self addChildViewController:[[HKPictureViewController alloc] init]];
    [self addChildViewController:[[HKWordViewController alloc] init]];
}
- (void)setupNavBar {
    // 左边按钮
    // 把UIButton包装成UIBarButtonItem.就导致按钮点击区域扩大
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithimage:[UIImage imageNamed:@"nav_item_game_icon"] highImage:[UIImage imageNamed:@"nav_item_game_click_icon"] target:self action:@selector(game)];
    
    // 右边按钮
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithimage:[UIImage imageNamed:@"navigationButtonRandom"] highImage:[UIImage imageNamed:@"navigationButtonRandomClick"] target:self action:@selector(game)];
    
    // titleView
    self.navigationItem.titleView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"MainTitle"]];
}

- (void)game {
    
}
/** scrollView */
- (void)setupScrollView
{
    // 不允许自动修改UIScrollView的内边距
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    UIScrollView *scrollView = [[UIScrollView alloc] init];
    scrollView.backgroundColor = [UIColor blueColor];
    scrollView.frame = self.view.bounds;
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.showsVerticalScrollIndicator = NO;
    scrollView.pagingEnabled = YES;
    scrollView.scrollsToTop = NO; // 点击状态栏的时候，这个scrollView不会滚动到最顶部
    scrollView.delegate = self;
    [self.view addSubview:scrollView];
    self.scrollView = scrollView;
    
    // 添加子控制器的view
    NSUInteger count = self.childViewControllers.count;
    CGFloat scrollViewW = scrollView.width;
    scrollView.contentSize = CGSizeMake(count * scrollViewW, 0);//设置左右滑动
}

/** 标题栏 */
- (void)setupTitlesView
{
    UIView *titlesView = [[UIView alloc] init];
    // 设置半透明背景色
    titlesView.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.5];
    titlesView.frame = CGRectMake(0, HK_NAVBAR_HEIGHT, self.view.width, 35);
    [self.view addSubview:titlesView];
    self.titlesView = titlesView;
    // 标题栏按钮
    [self setupTitleButtons];
    // 标题下划线
    [self setupTitleUnderline];
}

/**
 *  标题栏按钮
 */
- (void)setupTitleButtons
{
    // 文字
    NSArray *titles = @[@"全部", @"视频", @"声音", @"图片", @"段子"];
    NSUInteger count = titles.count;
    
    // 标题按钮的尺寸
    CGFloat titleButtonW = self.titlesView.width / count;
    CGFloat titleButtonH = self.titlesView.height;
    
    // 创建5个标题按钮
    for (NSUInteger i = 0; i < count; i++) {
        HKTitleButton *titleButton = [[HKTitleButton alloc] init];
        [titleButton addTarget:self action:@selector(titleButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.titlesView addSubview:titleButton];
        // frame
        titleButton.frame = CGRectMake(i * titleButtonW, 0, titleButtonW, titleButtonH);
        titleButton.tag = i;
        // 文字
        [titleButton setTitle:titles[i] forState:UIControlStateNormal];
        [titleButton setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
        [titleButton setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
    }
}
/**
 *  标题下划线
 */
- (void)setupTitleUnderline
{
    // 标题按钮
    HKTitleButton *firstTitleButton = self.titlesView.subviews.firstObject;
    // 下划线
    UIView *titleUnderline = [[UIView alloc] init];
    titleUnderline.height = 2;
    titleUnderline.y = self.titlesView.height - titleUnderline.height;
    titleUnderline.backgroundColor = [firstTitleButton titleColorForState:UIControlStateSelected];
    [self.titlesView addSubview:titleUnderline];
    self.titleUnderline = titleUnderline;
    // 切换按钮状态
    firstTitleButton.selected = YES;
    self.previousClickedTitleButton = firstTitleButton;
    [firstTitleButton.titleLabel sizeToFit]; // 让label根据文字内容计算尺寸
    self.titleUnderline.width = firstTitleButton.titleLabel.width + 10;
    self.titleUnderline.centerX = firstTitleButton.centerX;
}
#pragma mark - 监听
/**
 *  点击标题按钮
 */
- (void)titleButtonClick:(HKTitleButton *)titleButton
{
    // 重复点击了标题按钮
    if (self.previousClickedTitleButton == titleButton) {
        [[NSNotificationCenter defaultCenter] postNotificationName:HKTitleButtonDidRepeatClickNotification object:nil];
    }
    self.previousClickedTitleButton.selected = NO;
    titleButton.selected = YES;
    self.previousClickedTitleButton = titleButton;
    //优化加载方式，懒加载控制器
    NSUInteger index = titleButton.tag;
    [UIView animateWithDuration:0.25 animations:^{
        // 处理下划线
        self.titleUnderline.width = titleButton.titleLabel.width + 10;
        self.titleUnderline.centerX = titleButton.centerX;
        
        // 滚动scrollView
        CGFloat offsetX = self.scrollView.width * index;
        self.scrollView.contentOffset = CGPointMake(offsetX, self.scrollView.contentOffset.y);
    } completion:^(BOOL finished) {
        // 添加子控制器的view
        [self addChildVcViewIntoScrollView:index];
    }];
    #pragma mark - 设置index位置对应的tableView.scrollsToTop = YES， 其他都设置为NO
    for (NSUInteger i = 0; i < self.childViewControllers.count; i++) {
        UIViewController *childVc = self.childViewControllers[i];
        // 如果view还没有被创建，就不用去处理
        if (!childVc.isViewLoaded) continue;
        UIScrollView *scrollView = (UIScrollView *)childVc.view;
        if (![scrollView isKindOfClass:[UIScrollView class]]) continue;
        //if (i == index) { // 是标题按钮对应的子控制器
        //    scrollView.scrollsToTop = YES;
        //} else {
        //    scrollView.scrollsToTop = NO;
        //}
        scrollView.scrollsToTop = (i == index);
    }
}
#pragma mar - 数据源
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView.tag == 0) return 10;
    return 20;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ID = @"ID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ID"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        cell.backgroundColor = [UIColor clearColor];
    }
    cell.textLabel.text = [NSString stringWithFormat:@"test-%zd", indexPath.row];
    return cell;
}
#pragma mark - <UIScrollViewDelegate>
/**
 *  当用户松开scrollView并且滑动结束时调用这个代理方法（scrollView停止滚动的时候）
 */
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    // 求出标题按钮的索引
    NSUInteger index = scrollView.contentOffset.x / scrollView.width;
    // index == [0, 4]
    // 点击对应的标题按钮
    HKTitleButton *titleButton = self.titlesView.subviews[index];
    //HKTitleButton *titleButton = [self.titlesView viewWithTag:index];
    //此代码 索引为0时会报错(viewWithTag 递归查找，包括自己 先查找自己的tag，再查找子视图的tag，父视图默认tag为0，找到的是UIView而不是Button，所以setSelected方法找不到)
    [self titleButtonClick:titleButton];
}

/**
 *  当用户松开scrollView时调用这个代理方法（结束拖拽的时候）
 */
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    JKFunc;
}
#pragma mark - iOS-懒加载子控制器的View
/**
 *  添加第index个子控制器的view到scrollView中
 */
- (void)addChildVcViewIntoScrollView:(NSUInteger)index
{
    //取出按钮索引对应的控制器
    UIViewController *childVc = self.childViewControllers[index];
    // 如果view已经被加载过，就直接返回
    if (childVc.isViewLoaded) return;
    // 取出index位置对应的子控制器view
    UIView *childVcView = childVc.view;
    //  if (childVcView.superview) return;
    //  if (childVcView.window) return;
    // 设置子控制器view的frame
    CGFloat scrollViewW = self.scrollView.width;
    childVcView.frame = CGRectMake(index * scrollViewW, 0, scrollViewW, self.scrollView.height);
    // 添加子控制器的view到scrollView中
    [self.scrollView addSubview:childVcView];
    HKLog(@"--Index--%zd",index);
}
/**
 *  添加子控制器的view到scrollView中
 */
- (void)addChildVcViewIntoScrollView
{
    CGFloat scrollViewW = self.scrollView.width;
    NSUInteger index = self.scrollView.contentOffset.x / scrollViewW;
    // 取出index位置对应的子控制器view
    UIView *childVcView = self.childViewControllers[index].view;
    // 设置子控制器view的frame
    childVcView.frame = self.scrollView.bounds;
    // 添加子控制器的view到scrollView中
    [self.scrollView addSubview:childVcView];

}
@end
